<template>
    <div  class="BoxChart" style="margin-top:10px;">
        <div class="BoxChart_title">
            <Card style="height:350px;">
                <div slot="title">
                    <div style="margin-bottom:5px">{{chartconfig[indexID].name}}
                         <Poptip trigger="hover"  placement="top-start">
                            <Icon type="ios-paper-outline" style="margin-left:5px"/>
                            <span slot="content" :style="isColor">{{chartconfig[indexID].remark==''?"暂无备注":chartconfig[indexID].remark}}</span>
                        </Poptip>
                    </div>
                    <div style="font-size:12px">
                        <span>{{date}}</span>
                        <span v-if="JSON.parse(chartconfig[indexID].time).type=='relative'" class="vertical">|</span>
                        <span v-if="JSON.parse(chartconfig[indexID].time).type=='relative'">{{dynamicTime}}</span>
                    </div>
                </div>
                <a href="#" slot="extra">
                    <Dropdown trigger="click">
                        <a href="javascript:void(0)">
                            <i type="md-close" class="del iconfont icon-gengduo"  size="20"></i>
                        </a>
                        <Dropdown-menu slot="list" style="width:100px">
                            <Dropdown-item  disabled>小</Dropdown-item>
                            <Dropdown-item :selected='chartconfig[indexID].size=="normal"' @click.native='setWindow("normal")'>中</Dropdown-item>
                            <Dropdown-item :selected='chartconfig[indexID].size=="big"'  @click.native='setWindow("big")'>大</Dropdown-item>
                            <Dropdown-item  @click.native="set()" divided >设置</Dropdown-item>
                            <Dropdown-item  @click.native="delCharts(chartconfig[indexID].id)">删除</Dropdown-item>
                        </Dropdown-menu>
                    </Dropdown>
                </a>
                <Table class="aaa" ref="table" :loading="loading" :row-class-name="totalRowClass" height="220" :columns="tableColumns" :data="pager.data" border @on-sort-change="totalSort"></Table>
                <div style="margin: 10px;overflow: hidden">
                    <div style="float: right;">
                        <Page :total="resultSet.length" :current.sync="pager.current" :page-size="pager.size" show-total @change="changePage"></Page>
                    </div>
                </div>
            </Card>
        </div>
    </div>
</template>

<script type="text/ecmascript-6">
import {mapState} from 'vuex';
import setModule from '../components/setModule'
  export default {
    props:['chartconfig','indexID',"events","properties","measures","dashboardId","projectId"],
    components:{
        setModule
    },
    data() {
        return {
            loading:true,
            indicators:[],
            date:'',
            dateValue: [this.$sessionStore.getDay(-7),this.$sessionStore.getDay(0)],
				dateOptions: {
				shortcuts: [
					{
						text: '今天',
						value () {
							const end = new Date();
							const start = new Date();
							return [start, end];
						}
					},
					{
						text: '昨天',
						value () {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24);
							return [start, end];
						}
					},
					{
						text: '最近7天',
						value () {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
							return [start, end];
						}
					},
					{
						text: '最近一月',
						value () {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
							return [start, end];
						}
					},
					{
						text: '最近三月',
						value () {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
							return [start, end];
						}
					}
				]
                },
            tableColumns: [],
            table: {
                columns: [],
            },
            pager: {
                data: [],
                current: 1,
                size: 20
            },
            resultSet: [],
            config: {
				indicators: [{
					event: "",
					measure: [
						
					],
					filter: {
						condition: 'AND',
						rules: []
					}
				}],
				dimensions: [],
				filter: {
					condition: 'AND',
					rules: []
				},
				display: {
					orderby: '',
					order: 'DESC',
					limit: 1
				}
            },
            dynamicTime:''
        }
    },
    mounted(){
        let _that=this
        let times=JSON.parse(_that.chartconfig[_that.indexID].time)
            if(times.type == 'absolute'){
                times.values[0]=this.$sessionStore.getDay(-times.values[0])
                times.values[1]=this.$sessionStore.getDay(-times.values[1])
                this.date=times.values[0]+"~"+times.values[1]
               
            }else if(times.type == 'relative'){
                this.date=times.values[0]+"~"+times.values[1]
                let newdata1=this.dateDiff( times.values[0])
                let newdata2=this.dateDiff( times.values[1])
                if(this.$sessionStore.getDay(0)==times.values[1]&&this.$sessionStore.getDay(0)!==times.values[0]){
                    this.dynamicTime='最近'+newdata1+'天'
                }else if(this.$sessionStore.getDay(0)==times.values[1]&&this.$sessionStore.getDay(0)==times.values[0]){
                     this.dynamicTime='今日'
                }else {
                    this.dynamicTime='过去'+newdata2+'天~过去'+newdata1+'天'
                }
            }
       
        this.config=JSON.parse(_that.chartconfig[_that.indexID].config)
        // let timeQuantum={}
        // timeQuantum.start=times.values[0]
        // timeQuantum.end=times.values[1]
        // timeQuantum.unit=times.unit
        this.query()
       
    },
    computed:{
         isColor:function(){
            if(this.chartconfig[this.indexID].remark==''){
                return "color:#BFBFCD"
            }
        },
        propertyMap:function(){
            let propertyMap = {};
                for(let i = 0; i < this.properties.length; i++) {
                propertyMap[this.properties[i].name] = this.properties[i];
             }
            return propertyMap;
        },
        eventMap: function() {
            let eventMap = {};
                 for(let i = 0; i < this.events.length; i++) {
                    eventMap[this.events[i].name] = this.events[i];
                }
            return eventMap;
            },
        measureMap: function() {
            let measureMap = {};
                for(let i = 0; i < this.measures.length; i++) {
                measureMap[this.measures[i].name] = this.measures[i];
             }
            return measureMap;
        },
    },
    methods:{
        query(){
             this.$axios.post(this.$api.report + "/analysis/event",
                    {
                        time:{start: "2019-08-24", end: "2019-11-22", unit: "none"},
                        config:this.config
                    },
                    {
                        headers: {
                            "Authorization": "Bearer "+this.$sessionStore.fetch(),
                            "Accept": "application/json"
                        },
                        params: {
                            projectId: this.$store.state.projectId
                        }
                    }).then(response => {
                        if (response.status === 200) {
                            this.resultSet = response.data;
                            this.loading=false
                            this.updateIndicators()
                            this.updateTableColumns()
                            this.changePage(1);
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    }).finally(() => {
                       
                    });  
        },
        set(){
           this.$parent.$parent.$parent.$parent.updatamodal2(this.indexID,'set')
        },
        setWindow(col){
            this.$parent.$parent.$parent.$parent.changeSize(this.indexID,col)
        },
        totalSort: function(column) {
                this.config.display.orderby = column.key;
                this.config.display.order = column.order.toUpperCase();
                this.query()
                
            },
        totalRowClass: function(row, index) {
                if(index === 0 && this.showTotal) {
                    return "table-info-row";
                }
                return '';
            },
        updateTableColumns: function() {
            this.tableColumns.splice(0, this.tableColumns.length);
            if(this.config.dimensions.length === 0) {
                this.tableColumns.push({
                    title: '日期',
                    key: 'date',
                    sortable: false
                });
            }
            for(let i = 0; i < this.config.dimensions.length; i++) {
                if(this.config.dimensions[i] in this.propertyMap) {
                    this.tableColumns.push({
                        title: this.propertyMap[this.config.dimensions[i]].displayName,
                        key: this.config.dimensions[i],
                        sortable: false
                    });
                }
            }
            for(let i = 0; i < this.indicators.length; i++) {
                this.tableColumns.push({
                    title: this.indicators[i].label,
                    key: this.indicators[i].value,
                    sortable: 'custom'
                });
            }
        },
        updateIndicators: function() {
            this.indicators.splice(0, this.indicators.length);
            let obj = {};
            for(let i = 0; i < this.config.indicators.length; i++) {
                for(let j = 0; j < this.config.indicators[i].measure.length; j++) {
                    let eventName = this.config.indicators[i].event;
                    let measureName = this.config.indicators[i].measure[j].name;
                    if(!obj[eventName + "_" + measureName]) {
                        if(eventName in this.eventMap && measureName in this.measureMap) {
                            this.indicators.push({
                                label: this.eventMap[eventName].displayName + "的" + this.measureMap[measureName].displayName,
                                value: eventName + "_" + measureName
                            });
                            obj[eventName + "_" + measureName] = true;
                        }
                    }
                }
            }
            // if(this.config.display.orderby !== undefined && this.config.display.orderby !== "") {
            //     this.indicator = this.config.display.orderby;
            // } else {
            //     if(this.indicators.length > 0) {
            //         this.indicator = this.indicators[0].value;
            //     }
            // }
    
            let str=this.chartconfig[this.indexID].indicators.split(",")
           
                let newIndicators=[]
                for (let k = 0; k < this.indicators.length; k++) {
                   for (let o = 0; o < str.length; o++) {
                     if(this.indicators[k].value==str[o]){
                         newIndicators.push(this.indicators[k])
                     }
                   }
                }
                this.indicators=newIndicators
        },
        changePage: function(page) {
            this.pager.current = page;
            this.pager.data.splice(0, this.pager.data.length);
            for(let i = (this.pager.current - 1)*this.pager.size;
                i < Math.min(this.pager.current*this.pager.size, this.resultSet.length);i++){
                this.pager.data.push(this.resultSet[i]);
                }
            },
         dateDiff : function(sDate1) {
                var date2 = new Date();
                var date1 = new Date(Date.parse(sDate1.replace(/-/g,   "/")));
                var iDays = parseInt(Math.abs(date2.getTime()- date1.getTime()) /1000/60/60/24); 
                return iDays;
            },
        delCharts(del_id){
            let _that = this;
            this.$axios.delete(_that.$api.report +'/dashboard-pro/'+_that.dashboardId[0].id+'/block/'+del_id,
                {
                    headers: {
                        "Authorization": "Bearer "+this.$sessionStore.fetch(),
                        'Content-type': 'application/json'
                    },
                    params: {
                        projectId:_that.projectId
                    }
                }
            )
            .then(function(res){
                _that.$Message.info('删除成功');
                _that.chartconfig.map((item,index)=>{
                    if(item.id == del_id){
                        _that.chartconfig.splice(index,1);
                    }
                    return true; 
                })
            }).catch(function(err){
                console.log(err);
            })
        },
    }
  }
</script>

<style  scoped>
.vertical{
    font-weight: 700;
    margin: 0 5px;
}
</style>
